import axios from "axios";
import router from "@/router/index.js";

import {getToken} from "@/utils/token/index.js";
import {ElMessage} from "element-plus";

const baseURL = "http://localhost:8080/"
const request = axios.create({
    baseURL: baseURL,
    withCredentials: false,
    timeout: 30000
});

axios.defaults.headers['Content_Type'] = 'application/json?charset=utf-8'

request.interceptors.request.use((config) => {
    if (getToken("daocaoToken")) {
        config.headers['Daocao-Authorization'] = getToken("daocaoToken")
    }
    return config
}, (error) => {
    console.log(error)
    return Promise.reject(error)
})

request.interceptors.response.use((response) => {
    let {msg, code} = response.data;
    if (code == null) {
        return response
    } else if (code === 200) {
        return response
    } else if (code === 500) {
        ElMessage.error("服务器错误")
    } else if (code === 401) {
        ElMessage.error("权限不足")
    } else if (code === 403) {
        ElMessage.error("登录过期")
        window.sessionStorage.clear();
        router.push('/login')
    }
    return Promise.reject(msg)
}, (error) => {
    ElMessage.error(error)
    window.sessionStorage.clear();
    router.push('/login')
    return Promise.reject(error)
})

export default request